<template>
  <div class="img-box" @click="fileRef.click()">
    <input
      ref="fileRef"
      type="file"
      :accept="accept"
      style="display: none"
      @change="change"
    />
    <img class="max-img" v-if="src" :src="src" />
    <svg
      v-else
      class="w-6 h-6"
      fill="none"
      stroke="currentColor"
      viewBox="0 0 24 24"
      xmlns="http://www.w3.org/2000/svg"
    >
      <path
        stroke-linecap="round"
        stroke-linejoin="round"
        stroke-width="2"
        d="M4 16v1a3 3 0 003 3h10a3 3 0 003-3v-1m-4-8l-4-4m0 0L8 8m4-4v12"
      ></path>
    </svg>
  </div>
</template>
<script>
import { ref } from "vue";
import { notEmpty } from "@/utils/utils";

export default {
  props: {
    accept: {
      type: String,
      default: "image/png, image/jpeg, image/gif, image/jpg",
    },
    modelValue: [String, Object],
  },
  setup(props, { emit }) {
    const fileRef = ref(null),
      src = ref("");
    // 处理初值
    if (notEmpty(props.modelValue)) src.value = props.modelValue;
    // 处理图片预览
    const change = () => {
      const reader = new FileReader();
      const [file] = fileRef.value.files;
      reader.readAsDataURL(file);
      reader.onload = () => {
        src.value = reader.result;
      };
      // 更新绑定的值
      emit("update:model-value", file);
    };
    return {
      fileRef,
      change,
      src,
    };
  },
};
</script>
<style scoped>
.img-box {
  width: 80%;
  /* height: auto; */
  margin: 0 auto;
}
.max-img {
  width: 100%;
  margin: 0 auto;
}
</style>
